package com.crawler.harbour.common;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import com.alibaba.fastjson.JSONObject;
import com.crawler.harbour.dto.CostCode;
import com.crawler.harbour.dto.CostParametersDto;
import com.crawler.harbour.model.GGHGbiaozhun;
import com.crawler.harbour.utils.CookieUtil;
import com.crawler.harbour.utils.HtmlCleanerUtils;
import com.crawler.harbour.utils.MD5Util;
import com.crawler.harbour.utils.RuoKuai;
import com.crawler.harbour.utils.UrlUtil;
import com.google.common.collect.Lists;

import okhttp3.FormBody;
import okhttp3.FormBody.Builder;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 国际货柜码头费用爬取类
 *
 */
public class GJHGCostSpider extends CostSpider {
	static String SESSION = "";
	
	public GJHGCostSpider() {
		super();
	}
	public GJHGCostSpider(OkHttpClient client) {
		super(client);
	}
	
	@Override
	public List<GGHGbiaozhun> startCrawl(List<CostParametersDto> infos){
		List<GGHGbiaozhun> result = Lists.newArrayList();
		if(infos.isEmpty()) {
			return result;
		}
		String session=getSession();
		for(CostParametersDto info : infos) {
			GGHGbiaozhun cr=new GGHGbiaozhun();
	    	cr.setContainerNo(info.getContainerNo());
	    	cr.setLadingBillNo(info.getLadingBillNo());
	    	cr.setPortNo(info.getPortNo());
	    	cr.setResult("fail");
	    	cr.setId(info.getId());
	    	if(session==null) {
	    		result.add(cr);
	    		continue;
	    	}
	    	if(!session.equalsIgnoreCase(GJHGCostSpider.SESSION)) {
	    		GJHGCostSpider.SESSION = session;
	    		this.login(info, GJHGCostSpider.SESSION);
	    	}
	    	
	    	Builder formbodyBuilder = new FormBody.Builder();
	    	String loadingBillNo=info.getLadingBillNo()!=null?info.getLadingBillNo():"";
	    	String containerId=info.getContainerNo()!=null?info.getContainerNo():"";
	    	
	    	formbodyBuilder.add("invSysNo","");
	    	formbodyBuilder.add("invNo","");
	    	formbodyBuilder.add("blNo","");
	    	formbodyBuilder.add("containerId",containerId);
	    	formbodyBuilder.add("ioFlag","ALL");
	    	formbodyBuilder.add("startDate","");
	    	formbodyBuilder.add("endDate","");
	    	formbodyBuilder.add("submit", "查询");
	    	formbodyBuilder.add("actionUrl", "this");

	    	
	    	
	    	String postfix=";jsessionid="+CookieUtil.getValueByCookieName("JSESSIONID", GJHGCostSpider.SESSION);
	    	String url=UrlUtil.XICT_COST_URL2+postfix;
	  
	    	   Request request=new Request.Builder()
	   	    		//厦门集装箱码头的首页
	   	    		.url(url).header("referer", url)
	   	    		.post(formbodyBuilder.build())
	   	    		.build();
	    	   Response response = null;
	   	    try {
	   	    	response=client.newCall(request).execute();
	   			if (response.isSuccessful()) {
	   				String html=response.body().string();
	   				HtmlCleaner hc = new HtmlCleaner();
	   				TagNode rootNode = hc.clean(html);
	   				
	   				List<TagNode> rows = HtmlCleanerUtils.getNodesByXpath(rootNode, "//table[@class='quotation_size']//tr");
	   				
	   				for(int r=2; r<rows.size(); r=r+2) {
	   					TagNode targetNode = rows.get(r);
	   					TagNode outDateNode = rows.get(r-1);
	   				
		   				if(targetNode!=null) {
		   					String pageBillNum = targetNode.getChildTagList().get(1).getText().toString();
		   					if(!pageBillNum.contains(loadingBillNo)) {
		   						continue;
		   					}
		   				   //cr.setCarNo(HtmlCleanerUtils.getNodeText(targetNode, "//td[27]"));
		   				   cr.setResult("successs");	
		   				   
		   				   String unhandleOutDateStr=outDateNode.getText().toString();
		   				   
		   				   cr.setOutTime(pickOutDate(unhandleOutDateStr));
		   				   
		   				   String storageDay=HtmlCleanerUtils.getNodeText(targetNode, "//td[36]");
						   if(storageDay==null||storageDay.length()==0){
							   cr.setStorageDays("0");
						   }else{
							   cr.setStorageDays(storageDay);
						   }
//		   				   cr.setStorageDays(HtmlCleanerUtils.getNodeText(targetNode, "//td[36]"));
						   cr.setId(info.getId());
						   cr.setLadingBillNo(info.getLadingBillNo());
		   				   cr.setTotalFee(HtmlCleanerUtils.getNodeText(targetNode, "//td[5]"));
		   				   cr.addFee(CostCode._300001,HtmlCleanerUtils.getNodeText(targetNode, "//td[6]"));
		   				   cr.addFee(CostCode._300002,HtmlCleanerUtils.getNodeText(targetNode, "//td[7]"));
		   				   cr.addFee(CostCode._300003,HtmlCleanerUtils.getNodeText(targetNode, "//td[8]"));
		   				   cr.addFee(CostCode._300004,HtmlCleanerUtils.getNodeText(targetNode, "//td[9]"));
		   				   cr.addFee(CostCode._300027,HtmlCleanerUtils.getNodeText(targetNode, "//td[10]"));
		   				   cr.addFee(CostCode._300010,HtmlCleanerUtils.getNodeText(targetNode, "//td[11]"));
		   				   cr.addFee(CostCode._300012,HtmlCleanerUtils.getNodeText(targetNode, "//td[12]"));
		   				   cr.addFee(CostCode._300014,HtmlCleanerUtils.getNodeText(targetNode, "//td[13]"));
		   				   cr.addFee(CostCode._300015,HtmlCleanerUtils.getNodeText(targetNode, "//td[14]"));
		   				   cr.addFee(CostCode._300016,HtmlCleanerUtils.getNodeText(targetNode, "//td[15]"));
		   				   cr.addFee(CostCode._300020,HtmlCleanerUtils.getNodeText(targetNode, "//td[16]"));
		   				   cr.addFee(CostCode._300017,HtmlCleanerUtils.getNodeText(targetNode, "//td[17]"));
		   				   cr.addFee(CostCode._300008,HtmlCleanerUtils.getNodeText(targetNode, "//td[18]"));
		   				   cr.addFee(CostCode._300007,HtmlCleanerUtils.getNodeText(targetNode, "//td[19]"));
		   				   cr.addFee(CostCode._300009,HtmlCleanerUtils.getNodeText(targetNode, "//td[20]"));
		   				   cr.addFee(CostCode._300021,HtmlCleanerUtils.getNodeText(targetNode, "//td[21]"));
		   				   cr.addFee(CostCode._300022,HtmlCleanerUtils.getNodeText(targetNode, "//td[22]"));
		   				   cr.addFee(CostCode._300023,HtmlCleanerUtils.getNodeText(targetNode, "//td[23]"));
		   				   cr.addFee(CostCode._300024,HtmlCleanerUtils.getNodeText(targetNode, "//td[24]"));
		   				   cr.addFee(CostCode._300025,HtmlCleanerUtils.getNodeText(targetNode, "//td[25]"));
		   				   cr.addFee(CostCode._300026,HtmlCleanerUtils.getNodeText(targetNode, "//td[26]"));
		   				}
	   				}
	   			}
	   		} catch (IOException e) {
	   			e.printStackTrace();
	   		} catch (XPatherException e) {
	   			e.printStackTrace();
			}finally {
				if(response!=null) {
					response.close();
				}
			}
	   	 result.add(cr);
		}
		return result;
	}
	
	public boolean login(CostParametersDto info, String sessionId) {
		String code = getCode(sessionId);
		
		Builder formbodyBuilder = new FormBody.Builder();
		formbodyBuilder.add("userId", info.getUsername());
		String pwd = MD5Util.getMD5(info.getPwd().toUpperCase()).toLowerCase();
		formbodyBuilder.add("password", pwd);
		formbodyBuilder.add("checkId", code);
		String url = UrlUtil.XICT_LOGIN_URL;
		Request request=new Request.Builder()
   	    		.url(url)
   	    		.header("Referer", url)
   	    		.header("Cookie", sessionId)
   	    		.header("Upgrade-Insecure-Requests", "1")
   	    		.header("Content-Type", "application/x-www-form-urlencoded")
   	    		.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4882.400 QQBrowser/9.7.13059.400")
   	    		.post(formbodyBuilder.build())
   	    		.build();
		Response response=null;
		
		try {
			response = client.newCall(request).execute();
			if(!response.body().string().contains("<title>计费信息</title>")) {
				return false;
			}else {
				return true;
			}
		}catch(Exception ex) {
			ex.printStackTrace();
			return false;
		}
	}
	
	public String getCode(String sessionId) {
		String url = UrlUtil.XICT_VERIFY_CODE_URL;
		Request request=new Request.Builder()
   	    		//厦门集装箱码头的首页
   	    		.url(url).header("referer", url).header("Cookie", sessionId)
   	    		.get()
   	    		.build();
		Response response=null;
		try {
			response = client.newCall(request).execute();
			String codeResult = RuoKuai.createByPost( response.body().bytes());
	        JSONObject codeJson = JSONObject.parseObject(codeResult);
	        System.out.println(codeResult);
	       return codeJson.get("Result").toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public String getSession() {
		String session=null;
	    Request request=new Request.Builder()
	    		//厦门国际码头的首页
	    		.url(UrlUtil.GGHGBIAOZHUN+"?t="+new Date().getTime())
	    		.head().header("Cookie", GJHGCostSpider.SESSION)
	    		.build();
	    Response response=null;
	    try {
			 response=client.newCall(request).execute();
			if (response.isSuccessful()) {
				String setCookie="";
				List<String> cookieList= response.headers("Set-cookie");
				for (String cookie : cookieList) {
					setCookie+=cookie;
				}
				String pattern = "JSESSIONID=(\\w*);";
				Matcher m = Pattern.compile(pattern).matcher(setCookie);
				if(m.find()) {
					session=m.group(0);
				}
				if(session==null && GJHGCostSpider.SESSION!=null) {
					return GJHGCostSpider.SESSION;
				}
			}
		} catch (IOException e) {
		}finally {
			if(response!=null) {
				response.close();
			}
		}
	    return session;
	}
	@Override
	public String computeStorageDays(String inDay, String outDay) {
		// TODO Auto-generated method stub
		return null;
	}

	
	public String  pickOutDate(String unhandleOutDateStr){
		if(unhandleOutDateStr==null) return "";
		String outDate="";
		String pattern ="离泊:\\s*(\\d{4}-\\d{2}-\\d{2})";
		Matcher m = Pattern.compile(pattern).matcher(unhandleOutDateStr);
		if(m.find()){
			outDate=m.group(1);
		}
		
		return outDate;
	}
	


}
